<template>
  <div class="admin-stock-records">
    <div class="page-header">
      <h2>库存记录管理</h2>
      <p>管理员查看所有商品的入库出库记录</p>
    </div>

    <!-- 统计卡片 -->
    <div class="statistics-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ statistics.totalInRecords || 0 }}</div>
              <div class="stat-label">入库记录数</div>
            </div>
            <el-icon class="stat-icon in-icon"><Upload /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ statistics.totalOutRecords || 0 }}</div>
              <div class="stat-label">出库记录数</div>
            </div>
            <el-icon class="stat-icon out-icon"><Download /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ statistics.totalInQuantity || 0 }}</div>
              <div class="stat-label">总入库数量</div>
            </div>
            <el-icon class="stat-icon"><Plus /></el-icon>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-number">{{ statistics.totalOutQuantity || 0 }}</div>
              <div class="stat-label">总出库数量</div>
            </div>
            <el-icon class="stat-icon"><Minus /></el-icon>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 查询表单 -->
    <el-card class="search-card">
      <el-form :model="queryForm" inline>
        <el-form-item label="记录编号">
          <el-input v-model="queryForm.recordNo" placeholder="请输入记录编号" clearable />
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="queryForm.productName" placeholder="请输入商品名称" clearable />
        </el-form-item>
        <el-form-item label="商品编号">
          <el-input v-model="queryForm.productCode" placeholder="请输入商品编号" clearable />
        </el-form-item>
        <el-form-item label="记录类型">
          <el-select v-model="queryForm.recordType" placeholder="请选择记录类型" clearable>
            <el-option label="全部" value="" />
            <el-option label="入库" value="IN" />
            <el-option label="出库" value="OUT" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作员">
          <el-input v-model="queryForm.operatorName" placeholder="请输入操作员姓名" clearable />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="handleDateRangeChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="success" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-header">
        <h3>库存记录列表</h3>
        <div class="table-actions">
          <el-button type="primary" @click="loadStatistics">
            <el-icon><Refresh /></el-icon>
            刷新统计
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="recordNo" label="记录编号" width="180" />
        <el-table-column prop="productName" label="商品名称" min-width="150" />
        <el-table-column prop="productCode" label="商品编号" width="120" />
        <el-table-column prop="recordType" label="记录类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.recordType === 'IN' ? 'success' : 'warning'">
              {{ row.recordTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="操作数量" width="100" align="center" />
        <el-table-column prop="beforeStock" label="操作前库存" width="120" align="center" />
        <el-table-column prop="afterStock" label="操作后库存" width="120" align="center" />
        <el-table-column prop="unitCost" label="单位成本" width="100" align="center">
          <template #default="{ row }">
            <span v-if="row.unitCost">¥{{ row.unitCost }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalCost" label="总成本" width="100" align="center">
          <template #default="{ row }">
            <span v-if="row.totalCost">¥{{ row.totalCost }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="operatorName" label="操作员" width="100" />
        <el-table-column prop="createTime" label="操作时间" width="180" />
        <el-table-column prop="remark" label="备注" min-width="150" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, Upload, Plus, Minus } from '@element-plus/icons-vue'
import { adminStockApi } from '@/api/adminStock'

// 响应式数据
const loading = ref(false)
const tableData = ref([])
const dateRange = ref([])

// 查询表单
const queryForm = reactive({
  recordNo: '',
  productName: '',
  productCode: '',
  recordType: '',
  operatorName: '',
  startTime: '',
  endTime: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 统计信息
const statistics = ref({})

// 处理日期范围变化
const handleDateRangeChange = (dates) => {
  if (dates && dates.length === 2) {
    queryForm.startTime = dates[0]
    queryForm.endTime = dates[1]
  } else {
    queryForm.startTime = ''
    queryForm.endTime = ''
  }
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.page,
      size: pagination.size,
      ...queryForm
    }
    
    const response = await adminStockApi.getRecordsPage(params)
    if (response.success) {
      tableData.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.message || '查询失败')
    }
  } catch (error) {
    console.error('查询库存记录失败:', error)
    ElMessage.error('查询失败')
  } finally {
    loading.value = false
  }
}

// 加载统计信息
const loadStatistics = async () => {
  try {
    const params = {
      startTime: queryForm.startTime,
      endTime: queryForm.endTime
    }
    
    const response = await adminStockApi.getStatistics()
    if (response.success) {
      statistics.value = response.data || {}
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 查询
const handleSearch = () => {
  pagination.page = 1
  loadData()
  loadStatistics()
}

// 重置
const handleReset = () => {
  Object.keys(queryForm).forEach(key => {
    queryForm[key] = ''
  })
  dateRange.value = []
  pagination.page = 1
  loadData()
  loadStatistics()
}

// 导出
const handleExport = async () => {
  try {
    const params = {
      ...queryForm
    }
    
    const response = await adminStockApi.exportRecords(params)
    if (response.success) {
      // 这里可以处理导出逻辑，比如下载文件
      ElMessage.success('导出成功')
    } else {
      ElMessage.error(response.message || '导出失败')
    }
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

// 初始化
onMounted(() => {
  loadData()
  loadStatistics()
})
</script>

<style scoped>
.admin-stock-records {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  position: relative;
  overflow: hidden;
}

.stat-card :deep(.el-card__body) {
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.stat-icon {
  font-size: 40px;
  opacity: 0.8;
}

.in-icon {
  color: #67c23a;
}

.out-icon {
  color: #e6a23c;
}

.search-card {
  margin-bottom: 20px;
}

.search-card :deep(.el-form-item) {
  margin-bottom: 0;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-header h3 {
  margin: 0;
  color: #303133;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 